<template>
    <div>
        <div><h1>订单列表</h1></div>
        <div>
            <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
            >
                <el-form-item label="关键词">
                    <el-input
                        v-model="searchForm.keyWord"
                        placeholder="商品名称/ID/关键词"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="订单状态">
                    <el-select
                        v-model="searchForm.status"
                        placeholder="请选择订单状态"
                        style="width: 160px"
                        clearable
                    >
                        <el-option label="待支付" :value="0" />
                        <el-option label="已支付" :value="1" />
                        <el-option label="已发货" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单类型">
                    <el-select
                        v-model="searchForm.type"
                        placeholder="请选择订单类型"
                        style="width: 160px"
                        clearable
                    >
                        <el-option
                            v-for="item in orderTypeList"
                            :label="item.dictName"
                            :value="item.dictValue"
                            :key="item.dictId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadOrderList"
                        >搜索</el-button
                    >
                    <el-button type="primary" @click="onAddOrder"
                        >添加订单</el-button
                    >
                    <el-button type="success" @click="onExportOrder"
                        >导出订单</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table :data="orderList" stripe style="width: 100%">
                <el-table-column prop="orderId" label="ID" width="80" />
                <el-table-column prop="orderNo" label="订单编号" width="180" />
                <el-table-column prop="prodInfo" label="商品信息" width="180" />
                <el-table-column
                    prop="orderAmount"
                    label="订单金额"
                    width="100"
                />
                <el-table-column
                    prop="createTime"
                    label="创建时间"
                    width="160"
                />
                <el-table-column prop="createBy" label="消费者" width="100" />
                <el-table-column
                    prop="orderType"
                    label="订单类型"
                    width="100"
                    :formatter="formatter"
                />
                <el-table-column label="商品图片" width="280">
                    <template #default="scope">
                        <img
                            v-for="item in scope.row.imageList"
                            :src="item"
                            :key="item"
                            width="50"
                            height="50"
                        />
                    </template>
                </el-table-column>
                <el-table-column
                    prop="orderStatus"
                    label="订单状态"
                    width="100"
                >
                    <template #default="scope">
                        <el-tag v-if="scope.row.orderStatus == 0"
                            >未支付</el-tag
                        >
                        <el-tag type="success" v-if="scope.row.orderStatus == 1"
                            >已支付</el-tag
                        >
                        <el-tag v-if="scope.row.orderStatus == 2"
                            >待支付</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleViewOrder(scope.row)"
                            >详情</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px">
            <el-pagination
                v-model:current-page="searchForm.pageNum"
                v-model:page-size="searchForm.pageSize"
                :page-sizes="[2, 4, 6, 8]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <div>
            <!-- 新增订单对话框 -->
            <el-dialog v-model="dialogFormVisible" title="新增订单" width="700">
                <el-form :model="form">
                    <el-form-item
                        label="选择商品"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.infoId"
                            placeholder="请选择要购买的商品"
                        >
                            <el-option
                                v-for="item in prodInfoList"
                                :label="item.prodName"
                                :value="item.infoId"
                                :key="item.infoId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="购买数量"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.buyNum" autocomplete="off" />
                    </el-form-item>
                    <div>
                        <el-button type="primary" @click="addProdInfo"
                            >添加</el-button
                        >
                    </div>
                    <div>
                        <el-table
                            :data="buyInfoList"
                            stripe
                            style="width: 100%"
                        >
                            <el-table-column
                                prop="prodId"
                                label="商品ID"
                                width="100"
                            />
                            <el-table-column
                                prop="prodName"
                                label="商品名称"
                                width="160"
                            />
                            <el-table-column
                                prop="prodPrice"
                                label="商品价格"
                                width="120"
                            />
                            <el-table-column
                                prop="buyNum"
                                label="购买数量"
                                width="120"
                            />
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        type="danger"
                                        @click="onDeleteProdInfo(scope.row)"
                                        >删除</el-button
                                    >
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div>总价:{{ totalAmount }} 元</div>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button type="primary" @click="onSubmitAddOrder">
                            添加订单
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import {
    getOrderList,
    getProdInfoList,
    addOrder,
    getDictList,
} from "@/api/api";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from 'vue-router';

const router = useRouter();

const orderList = ref([]);
const searchForm = ref({
    pageNum: 1,
    pageSize: 2,
    keyWord: null,
    status: null,
    type: null,
});
const total = ref(0);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
    infoId: null,
    buyNum: 1,
});
const prodInfoList = ref([]);
const buyInfoList = ref([]);
const totalAmount = ref(0);
const userId = ref(0);

const orderTypeList = ref([]);

// 导出订单列表
const onExportOrder = () => { 
    console.log('onExportOrder');
    let url = "http://localhost:9011/shop/order/exportOrderList/"+userId.value;
    window.open(url);
};



const formatter = (row: any) => {
    let name = "未知";
    orderTypeList.value.forEach((item: any) => {
        if (item.dictValue == row.orderType) {
            name = item.dictName;
        }
    });

    return name;
};

// 查看订单详情
const handleViewOrder = (row: any) => {
    console.log("handleViewOrder", row);
    sessionStorage.setItem("orderId", row.orderId);
    router.push('/home/orderinfo');
};

// 提交添加订单
const onSubmitAddOrder = () => {
    addOrder(buyInfoList.value).then((res) => {
        console.log("res", res);
        if (res.data.code == 200) {
            ElMessage.success("新增订单成功");
            dialogFormVisible.value = false;
            loadOrderList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 添加商品到购物车
const addProdInfo = () => {
    prodInfoList.value.forEach((item) => {
        if (item.infoId === form.value.infoId) {
            item.buyNum = form.value.buyNum;
            buyInfoList.value.push(item);
        }
    });

    // 动态计算订单总价
    totalAmount.value = 0.0;
    buyInfoList.value.forEach((item) => {
        totalAmount.value += item.prodPrice * item.buyNum;
    });
};

const onDeleteProdInfo = (row: any) => {
    console.log("onDeleteProdInfo", row);
    buyInfoList.value.forEach((item, index) => {
        if (item.infoId === row.infoId) {
            buyInfoList.value.splice(index, 1);
        }
    });
    // 动态计算订单总价
    totalAmount.value = 0.0;
    buyInfoList.value.forEach((item) => {
        totalAmount.value += item.prodPrice * item.buyNum;
    });
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    searchForm.value.pageSize = val;
    loadOrderList();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    searchForm.value.pageNum = val;
    loadOrderList();
};

// 显示添加订单对话框
const onAddOrder = () => {
    console.log("新增订单");
    buyInfoList.value = [];
    form.value = {
        infoId: null,
        buyNum: 1,
    };
    totalAmount.value = 0.0;
    dialogFormVisible.value = true;
};

// 订单分页列表
const loadOrderList = () => {
    getOrderList(searchForm.value).then((res) => {
        if (res.data.code == 200) {
            orderList.value = res.data.data.records;
            total.value = res.data.data.total;
        }
    });
};

// 页面加载钩子函数
onMounted(() => {
    loadOrderList();
    // 获取商品信息列表
    getProdInfoList().then((res) => {
        if (res.data.code == 200) {
            prodInfoList.value = res.data.data;
        }
    });
    // 获取订单状态列表 orderTypeList
    getDictList(4).then((res) => {
        if (res.data.code == 200) {
            orderTypeList.value = res.data.data;
        }
    });

    // 获取用户ID
    let u = sessionStorage.getItem("user");
    let user = JSON.parse(u);
    userId.value = user.userId;
});
</script>

<style scoped></style>
